package com.lenovo.lcdm.dcm.config.login;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;
import com.lenovo.lcdm.dcm.common.context.LcdmUserContext;
import com.lenovo.lcdm.dcm.common.context.UserContext;
import com.lenovo.lcdm.common.exception.InvalidTokenException;
import com.lenovo.lcdm.dcm.common.token.TokenSupport;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.lenovo.lcdm.team.entity.TeamUser;


/**
 * @author huanghr2
 * <p>
 * 1、将当前用户存入上下文
 * 2、注入用户信息到Logback日志
 */
@Slf4j
public class SessionInterceptor implements HandlerInterceptor {

//    @Autowired
//    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 获取token
        String token = request.getHeader(TokenSupport.TOKEN_HEADER_KEY);
        if (CharSequenceUtil.isEmpty(token)) {
            log.info("SessionInterceptor no token, url:{}", request.getRequestURI());
            throw new InvalidTokenException();
        }
        String itCode = token;
//        String itCode = TokenSupport.getClaim(token, TokenSupport.JWT_KEY_IT_CODE).asString();
        if (StrUtil.isEmpty(itCode)) {
            throw new InvalidTokenException();
        }

        // 获取用户信息
//        Object userObj = redisUtil.get(String.format(RedisConstants.USER_INFO, itCode));
//        if (userObj == null) {
//            throw new InvalidTokenException();
//        }

        TeamUser userDto = new TeamUser();
        userDto.setItCode(itCode);
//        PlmUser userDto = JSONObject.parseObject(userObj.toString(), PlmUser.class);
        //TODO 临时方案
        UserContext.putItCode(userDto.getItCode());
        LcdmUserContext.putUser(userDto);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        LcdmUserContext.clear();
        UserContext.clear();
    }
}
